package com.wuchengdong.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wuchengdong.web.extend.utils.R;
import com.wuchengdong.web.pojo.Order;
import com.wuchengdong.web.pojo.Payment;
import com.wuchengdong.web.service.OrderService;
import com.wuchengdong.web.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/payment")
public class PaymentController {
    @Autowired
    PaymentService paymentService;
    @Autowired
    OrderService orderService;

    @GetMapping
    public R<List<Payment>> getAll() {
        return R.success(paymentService.list());
    }

    @GetMapping("/getById")
    public R<Payment> getById(Payment payment) {
        return R.success(paymentService.getById(payment.getId()));
    }

    /**
     * 调用时机：预约时支付定金后，直接创建 success状态的支付记录，
     */
    @PostMapping
    public R<String> save(@RequestBody Payment payment) {
        paymentService.save(payment);
        if (Objects.equals(payment.getStatus(), "success")) {
            Order order = orderService.getById(payment.getOrderId());

            String status = switch (order.getPaymentStatus()) {
                case "init" -> "half_paid";
                case "half_paid" -> "paid";
                default -> null;
            };
            orderService.update(
                    new LambdaUpdateWrapper<Order>()
                            .set(status != null, Order::getPaymentStatus, status)
                            .eq(Order::getId, payment.getOrderId())
            );
        }
        return R.success(payment.getId().toString());
    }

    /**
     * 调用时机：支付尾款时，订单早已经被创建，此时只需更新支付记录状态即可
     */
    @PostMapping("/pay")
    public R<String> pay(@RequestBody Payment payment) {
        paymentService.update(
                new LambdaUpdateWrapper<Payment>()
                        .eq(Payment::getId, payment.getId())
                        .set(Payment::getStatus, "success")
        );
        // 扫描对应订单表 更新Order状态
        Integer orderId = paymentService.getById(payment.getId()).getOrderId();
        Order order = orderService.getById(orderId);
        List<Payment> paymentList = paymentService.list(
                new LambdaQueryWrapper<Payment>().eq(Payment::getOrderId, order.getId())
        );
        BigDecimal totalPrice = order.getTotalPrice();
        // 如果所有的支付记录总和大于订单价格，则更新订单状态为paid
        for (Payment payment1 : paymentList) {
            totalPrice = totalPrice.subtract(payment1.getAmount());
        }
        if (totalPrice.compareTo(BigDecimal.ZERO) == 0) {
            orderService.update(
                    new LambdaUpdateWrapper<Order>()
                            .eq(Order::getId, orderId)
                            .set(Order::getPaymentStatus, "paid")
            );
        }
        return R.success("支付成功");
    }

}
